package com.drei.wolke.oauth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.stereotype.Component;

import com.drei.wolke.oauth2.authorize.AuthorizeConfigManager;


/**
 * @author 作者 owen E-mail: 624191343@qq.com
 * @version 创建时间：2018年1月31日 下午9:07:14 类说明
 */
@ComponentScan
@Component
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	
	
	@Autowired
	private AuthorizeConfigManager authorizeConfigManager;
	
	@Autowired
    private OAuth2WebSecurityExpressionHandler expressionHandler;
	 

	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/health","/user","/auth/**");
	}

	  /**
     * 配置解决 spring-security-oauth问题
     * https://github.com/spring-projects/spring-security-oauth/issues/730
     *
     * @param applicationContext ApplicationContext
     * @return OAuth2WebSecurityExpressionHandler
     */
    @Bean
    public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
        OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
        expressionHandler.setApplicationContext(applicationContext);
        return expressionHandler;
    }
	
    
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.expressionHandler(expressionHandler);
    }

	 

	@Override
	// 限制访问角色的权限
	public void configure(HttpSecurity http) throws Exception {
				
		http.csrf().disable() ;
        //限制调用"/getUser"方法（可以添加多个）
//          .antMatchers(HttpMethod.GET,"/{id}")
//          //设置可以调用上述方法的角色（可以添加多个）
//          .hasRole("ADMIN")
         
		authorizeConfigManager.config(http.authorizeRequests());
	}
	/*
	 * //无访问角色限制
	 * 
	 * @Override public void configure(HttpSecurity http) throws Exception{
	 * http.authorizeRequests().anyRequest().authenticated(); }
	 */

}
